const app = getApp();
const db = wx.cloud.database().collection("groupnews")

Page({
  data:{
    filmName:'',
    imgUrl:'',
    tempImgUrl: '' // 用于保存暂存图片路径
  },
  //生命周期函数——监听页面显示
  onShow:function(){
    //其它页面获取用户信息
    console.log(app.globalData.userInfo)
  },

  handleUpload() {
    let that = this;
    wx.chooseImage({
      success: chooseResult => {
        const tempImgUrl = chooseResult.tempFilePaths[0];
        that.setData({
          tempImgUrl: tempImgUrl
        });
      },
    });
  },

  publishGroupNews() {
    const filmName = this.data.filmName;
    const tempImgUrl = this.data.tempImgUrl;

    if (!filmName || !tempImgUrl) {
      wx.showToast({
        title: '请输入片名并上传海报',
        icon: 'error'
      });
      return;
    }

    wx.showLoading({
      title: '上传中',
    });
    // 上传图片到云存储
    wx.cloud.uploadFile({
      cloudPath: 'groupnews/' + (new Date()).valueOf() + '.png',
      filePath: tempImgUrl,
      success: res => {
        console.log('上传成功', res)
        wx.hideLoading();
        const imgUrl = res.fileID;
        // 上传成功后再提交到数据库
        db.add({
          data: {
            title: filmName,
            picture_url: imgUrl
          },
          success: res => {
            console.log('数据添加成功', res);
            this.setData({
              filmName: '',
              tempImgUrl: '' // 清空暂存图片路径
            });
            wx.showToast({
              title: '数据添加成功',
              icon: 'success'
            });
          },
          fail: err => {
            console.error('数据添加失败', err);
            wx.showToast({
              title: '数据添加失败，请重试',
              icon: 'none'
            });
          }
        });
      },
      fail: err => {
        console.error('上传失败', err);
        wx.hideLoading();
        wx.showToast({
          title: '上传失败，请重试',
          icon: 'none'
        });
      }
    });
  },

  onUnload: function() {
    const pages = getCurrentPages(); 
    if (pages.length >= 2) {
      const prevPage = pages[pages.length - 2]; 
      if (prevPage.getImageList) {
        prevPage.getImageList(); 
      }
    }
  }
});
